# -- coding: utf-8 --
# @time : 2023/4/24
# @author : 周梦泽
# @file : test.py
# @software: pycharm
"""
测试
"""

import pandas as pd
from common.utils.web_page_util import Tap
from common.utils.web_page_util import create_page
import unittest
from promotion import AddCommodity
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc.gjc_data import GetData
from autoTask.taobao.sycm.utils.csv_merge import read_csv
from common.utils.ExcelUtil import del_english_keywords
from autoTask.taobao.sycm.gjc.competitorGoodKey.publicResource import CategorySearch
from autoTask.taobao.sycm.gjc.competitorGoodKey import CompetitorGoodKey
from autoTask.taobao.taobao_login import Login
from autoTask.core.taskMapping import task_gjc_hyc_run
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc_hyc_main.data_clean_main import gjc_hyc_data
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc_hyc_main.gjc_hyc_main_run import run
import xlwings as xw
from common.utils.ExcelUtil import xw_del_sheet
import pygetwindow as gw
from pywinauto import application
import retrying
import random
from PIL import Image
import requests
from io import BytesIO
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.drawing.image import Image as openpyxl_image
from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc.gjc_data_2 import GetData

# from autoTask.taobao.sycm.gjc.gjc_hyc_robot.gjc.gjc_data import GetData

data_params = {
    # "account": "赫巴兹直销企业店:数据",
    # "password": "aa123456",
    # "account": "赫巴兹直销企业店",
    # "password": "zty1213",
    "account": "赫巴兹旗舰店:开发",
    "password": "hbz18374844582",

    "searchContent": "奶锅",
    # "tableTopic": ["麦饭石", "不粘锅", "炒锅", "炒菜锅", "家用", "电磁炉"],
    "tableTopic": [],
    "isOperationTitle": True,
    "isTestExecute": True,
    "isAutoAppendKeyWord": True,
    "rmEnglish": True,
    "relatedDay": 7,
    # "hotTermDay": 30,
    "hotTermDay": 7,
    "dataWord": "搜索词",
    "dealValue": 1000,
    "payNum": 30,
    "price": 128,
    "percent": 60,
    "priceCap": 1,
    "blockWords": [
        "苏泊尓",
        "迈巴勒",
        "乌兹别克斯坦",
        "章丘",
        "官方",
        # "空气炸锅",
        "炊大皇",
        "康巴赫",
        "铸铁锅",
        "树可",
        "卡罗特",
        "三禾",
        # "wmf",
        # "铁",
        "九阳",
        # "陶",
        "双立",
        "帝",
        "荣",
        "爱",
        "乐",
        "角",
        "迈巴勒",
        "乌兹别克斯坦",
        "迈巴赫",
        "厨之翼",
        "鹅妈妈",
        "金嫂子",
        "马克西姆",
        "美的",
        "温仑山",
        "网易严选",
        "奥康达",
        "德萨克",
        "吹大王",
        "宜家",
        "张小泉",
        "维氏",
        "奥克斯",
        "双喜",
        "欧莱克",
        "志高",
        "松下",
        "泊尔",
        "摩动",
        "神州",
        "黄老大",
        "康宁",
        "摩兰德",
        "龙泉",
        "王麻子",
        "十八子",
        "陈枝记",
        "18子",
        "狂鲨",
        "孙兴",
        "李培德",
        "葛华",
        "摩飞",
        "七彩叮当",
        "中康",
        "神田",
        "华邦",
        "宏江",
        "中福",
        "窒化",
        "黄老大",
        "陆川铁人牌",
        "旗舰",
        "康硕士",
        "维亿",
        "小帅锅",
        "吉川",
        "顺达",
        "揭宝",
        "厨之友",
        # "一层",
        # "二层",
        # "三层",
        # "四层",
        # "五层",
        # "六层",
        # "双层",
        # "商用",
        "洛德",
        # "陶土",
        "欧洛德"
        # "小蒸锅"
    ],
    "dealNum": 10000,
    "hotIndex": 4,
    "searchNum": 10000,
    "payRate": 10.1,
    "numOfPay": 501,
    "matchesType": "精准匹配",
    "targetProductMap": [
        {
            "productId": "671901195976",
            "titlePrefix": "",
            "titleSuffix": "",
            "titleMaxLength": 60,
            "delPromotionWord": False,
            "ignoreCuts": [
                "陶",
                "角",
                "电池",
                "蒸",
                "可用"
            ]
        }

    ]
}
data_params2 = {"account": "赫巴兹直销企业店:数据", "password": "aa123456", "searchContent": "贴板/菜板",
                "isOperationTitle": False, "isAutoAppendKeyWord": False, "dataWord": "搜索词",
                "dealValue": 1000, "payNum": 30, "price": 128,
                "blockWords": ["苏泊尓", "迈巴勒", "乌兹别克斯坦", "章丘", "官方", "炊大皇", "康巴赫",
                               "铸铁锅", "树可", "卡罗特", "三禾", "wmf", "铁", "九阳", "陶", "双立", "帝",
                               "荣", "爱", "乐", "角", "迈巴赫", "厨之翼", "鹅妈妈", "金嫂子", "马克西姆",
                               "美的", "温仑山", "网易严选", "奥康达", "德萨克", "吹大王", "宜家", "张小泉",
                               "维氏", "奥克斯", "双喜", "欧莱克", "志高", "松下", "泊尔", "摩动", "神州",
                               "黄老大", "康宁", "摩兰德", "龙泉", "王麻子", "十八子", "陈枝记", "18子",
                               "狂鲨", "孙兴", "李培德", "葛华", "摩飞", "七彩叮当", "中康", "神田", "华邦",
                               "宏江", "中福", "窒化", "陆川铁人牌", "旗舰", "康硕士", "维亿", "小帅锅",
                               "吉川", "顺达", "揭宝", "厨之友", "商用", "洛德", "陶土", "欧洛德", "小蒸锅",
                               '黄小厨', '小熊', '焠大皇'], "dealNum": 10000,
                "hotIndex": 5, "searchNum": 10000, "payRate": 10, "numOfPay": 500, "matchesType": "精准匹配",
                "targetProductMap": [
                    {"productId": "671777880493", "competing1": "626549074416", "competing2": "559916143244",
                     "titlePrefix": "\t 格洛恩", "titleSuffix": "", "titleMaxLength": 60, "ignoreCuts": []}],
                "rmEnglish": True, "percent": 60, "priceCap": 1, "dateCycle": 7, "isAppendCompeting": True,
                "competingMinVisits": 10, "competingMinRoi": 0}
excel_path = r"D:\python_code\drissionpage\DownloadData\sycm_table\gjc_hyc_data_clean\result\gjc_hyc_data_2023-05" \
             r"-23_11-51-17.xlsx"

param_ = {
    "taskId": "4",
    "taskName": "生意参谋-关键词-行业词",
    "param": {
        "account": "中山杰特电器:星星",
        "password": "yzt123456",
        # "account": "赫巴兹直销企业店",
        # "password": "zty1213",
        "searchContent": "炒锅",
        "isOperationTitle": True,
        "isAutoAppendKeyWord": True,
        "isTestExecute": True,
        "dataWord": "搜索词",
        "tableTopic": [
            "蜂窝"
        ],
        "dealValue": 1000,
        "payNum": 30,
        "price": 128,
        "blockWords": [
            "苏泊尓",
            "迈巴勒",
            "乌兹别克斯坦",
            "章丘",
            "官方",
            "炊大皇",
            "康巴赫",
            "铸铁锅",
            "树可",
            "卡罗特",
            "三禾",
            "九阳",
            "双立",
            "帝",
            "荣",
            "爱",
            "乐",
            "角",
            "迈巴赫",
            "厨之翼",
            "鹅妈妈",
            "金嫂子",
            "马克西姆",
            "美的",
            "温仑山",
            "网易严选",
            "奥康达",
            "德萨克",
            "吹大王",
            "宜家",
            "张小泉",
            "维氏",
            "奥克斯",
            "双喜",
            "欧莱克",
            "志高",
            "松下",
            "泊尔",
            "摩动",
            "神州",
            "黄老大",
            "康宁",
            "摩兰德",
            "龙泉",
            "王麻子",
            "十八子",
            "陈枝记",
            "18子",
            "狂鲨",
            "孙兴",
            "李培德",
            "葛华",
            "摩飞",
            "七彩叮当",
            "中康",
            "神田",
            "华邦",
            "宏江",
            "中福",
            "窒化",
            "陆川铁人牌",
            "旗舰",
            "康硕士",
            "维亿",
            "小帅锅",
            "吉川",
            "顺达",
            "揭宝",
            "厨之友",
            "洛德",
            "欧洛德",
            "铁"
        ],
        "dealNum": 10000,
        "hotIndex": 1,
        "searchNum": 10000,
        "payRate": 10,
        "numOfPay": 500,
        "matchesType": "精准匹配",
        "targetProductMap": [
            {
                "productId": "671777880493",
                "competing1": "684927851841",
                "competing2": "556907022467",
                "titlePrefix": "格洛恩316蜂窝",
                "titleSuffix": "炒锅",
                "titleMaxLength": 60,
                "ignoreCuts": []
            }
        ],
        "rmEnglish": True,
        "percent": 99,
        "priceCap": 1,
        "dateCycle": 7,
        "isAppendCompeting": True,
        "competingMinVisits": 10,
        "competingMinRoi": 0
    }
}


class Test(unittest.TestCase):

    def test_add_commodity(self):
        param = dict(param_.get('param'))
        # gjc_hyc_data(params_data=param)
        test_add_commodity = AddCommodity(param, excel_path)
        test_add_commodity.add_keywords()
        # test_add_commodity.modify_price(percent=60, price_cap=1)

    def test_General(self):
        # pass
        page = create_page()
        Tap(ele="x:/html/body/div[@class='el-dialog__wrapper xws-dialog-custom-class'][last()]/div/div[1]/button/i",
            msg="点击关闭小旺神失败", before_delay=(3, 5))(page)
        # p = page.ele('请登录')
        # MockTap(ele=p, msg='点击跳转登录页失败', before_delay=(2, 4), reduce_scope=(10, 5))(page)
        # run(data_params)
        # pass
        # 2023-05-11 15:51:38,228 - ERROR - 'builtin_function_or_method' object is not subscriptable
        # time.sleep(2)
        # Tap(ele="x://div[contains(@mxs, ':b')]/a[contains(@class, 'btn btn-brand mr10')]", before_delay=(2, 4))(page)
        # page('x://*[@id="mx_5676_main_table"]').scroll.to_top()
        # test_add_commodity = AddCommodity(data_params, excel_path)
        # test_add_commodity.del_promotion_word(page)
        # test_add_commodity.del_promotion_word(page)
        # test_add_commodity.modify_price(page, percent=60, price_cap=1)
        # Tap("x://div[contains(@class, 'keyword-popup')]//div[contains(@mxv, 'multiplyType')]")(page)
        # page.scroll.to_location(300, 50)
        # word_div = page.eles("x://tbody/tr[contains(@class, 'hYME_')]")
        # for index, word in enumerate(word_div):
        #     Tap(word.ele("x:/td[contains(@mxa, ':o')]/i"), before_delay=(2, 4))(page)
        #     time.sleep(2)

        # pass

    def test(self):
        print(self.test_General())

    def test_main_run(self):
        #     # page = create_page()
        #     # data = pd.read_csv('7天搜索排行.csv')
        #     # getdata = GetData(data_params)
        #     # getdata.deep_analysis(hot_term_day=7, data=data)
        #     total_df = read_csv(folder_path=r'D:\python_code\drissionpage\DownloadData\sycm_table\gjc\gjc_data')
        #     total_df = total_df.drop_duplicates(subset='关键词', keep='first')
        #     total_df.replace('-', float(0), inplace=True)
        #     # log_.info('屏蔽关键词')
        param = dict(param_.get('param'))
        block_words = param.get('blockWords')
        # print(block_words)
        my_string = ','.join(block_words)
        print(my_string)

    #     print(block_words)
    #     mask = False
    #     for block_word in block_words:
    #         mask |= total_df['关键词'].str.contains(block_word)
    #     total_df = total_df[~mask]
    #     total_df = del_english_keywords(total_df, '关键词')
    #
    #     total_df[['交易金额', '点击人数', '支付人数', '客单价', '访客平均价值']] = total_df[
    #         ['交易金额', '点击人数', '支付人数', '客单价', '访客平均价值']].astype('float64')
    #     data_df = total_df[
    #         (total_df['交易金额'] >= 500)
    #         & (total_df['点击人数'] >= 50)
    #         & (total_df['支付人数'] >= 5)
    #         & (total_df['客单价'] >= 20)
    #         & (total_df['访客平均价值'] >= 5)
    #         ]
    #
    #     data_df.to_excel('相关分析.xlsx', index=False)

    def test_get_data2(self):
        for search_content in ["煎锅/平底锅", "汤锅", "压力锅/高压锅", "奶锅", "蒸锅"]:

            data_params2['searchContent'] = search_content
            getdata = GetData(data_params2)
            getdata.start_run()
            search_content = search_content.replace(r'/', '_')
            print(search_content)
            excel_name = search_content
            total_df = read_csv(folder_path=r'D:\python_code\drissionpage\DownloadData\sycm_table\gjc\gjc_data')

            total_df.replace('-', float(0), inplace=True)

            with pd.ExcelWriter(f'{excel_name}.xlsx', engine='openpyxl') as writer:
                sheet_name = "原数据"
                total_df.to_excel(writer, sheet_name=sheet_name, index=False)

            total_df = total_df.drop_duplicates(subset='关键词', keep='first')
            # 去重
            with pd.ExcelWriter(f'{excel_name}.xlsx', engine='openpyxl', mode='a') as writer:
                sheet_name = "去重复数据后"
                total_df.to_excel(writer, sheet_name=sheet_name, index=False)
            print('屏蔽关键词')
            block_words = data_params2.get('blockWords')

            # print(block_words)
            mask = False
            for block_word in block_words:
                mask |= total_df['关键词'].str.contains(block_word)
            total_df = total_df[~mask]
            total_df = del_english_keywords(total_df, '关键词')
            with pd.ExcelWriter(f'{excel_name}.xlsx', mode='a', engine='openpyxl') as writer:
                sheet_name = "机器屏蔽关键词后"
                total_df.to_excel(writer, sheet_name=sheet_name, index=False)
            total_df[
                ['交易金额', '点击人数', '支付人数', '客单价', '访客平均价值', '搜索人数', '搜索人数/在线商品数']] = \
                total_df[
                    ['交易金额', '点击人数', '支付人数', '客单价', '访客平均价值', '搜索人数',
                     '搜索人数/在线商品数']].astype(
                    'float64')

            data_df = total_df[
                (total_df['交易金额'] >= 500)
                & (total_df['支付人数'] >= 3)
                & (total_df['客单价'] >= 100)
                & (total_df['访客平均价值'] >= 3)
                # 交易金额大于前1/2的标黄色
                # 搜索人数大于前1/2的标黄色
                # 搜索人数/在线商品数在没有黄色的条件下，小于1的去除
                # 关键字长度大于28的去除
                # 屏蔽词去除
                # & (total_df['点击人数'] >= 50)
                # 表格分为:原数据/去重后表格/机器筛选后
                ]
            idx_to_drop = data_df[data_df['关键词'].str.len() > 28].index

            # 删除符合条件的行
            data_df = data_df.drop(idx_to_drop)
            col1_median = data_df['搜索人数'].median()
            col2_median = data_df['交易金额'].median()
            highlight_rows = data_df[(data_df['搜索人数'] > col1_median) | (data_df['交易金额'] > col2_median)].index
            mask = (data_df['搜索人数/在线商品数'] >= 1) | (data_df.index.isin(highlight_rows))
            data_df = data_df.loc[mask]
            # print(len(highlight_rows))
            # print(highlight_rows)
            highlight_style = 'background-color: yellow'

            # 使用 style 属性和 applymap() 方法来将需要标黄的行标黄
            styled_df = data_df.style.applymap(lambda x: highlight_style, subset=pd.IndexSlice[highlight_rows, :])

            # styled_df = data_df.style.apply(self.highlight_greater_than_half, columns=['搜索人数', '交易金额'], axis=None)
            # print(yellow_index)

            # 将样式化的DataFrame保存为Excel文件

            with pd.ExcelWriter(f'{excel_name}.xlsx', mode='a', engine='openpyxl') as writer:
                sheet_name = "条件筛选筛选后"
                styled_df.to_excel(writer, sheet_name, index=False)

    def test_img2excel(self):
        # 创建 DataFrame，并将图片链接存储在某个列中

        # 样例数据
        data = {
            'Name': ['Image1', 'Image2'],
            'Image URL': [
                'https://gw.alicdn.com/imgextra/i1/1910949840/O1CN01kCWzkG2MYm3h4SgkH_!!1910949840.jpg',
                'https://gw.alicdn.com/imgextra/i3/1114217613/O1CN01au1agB266o3xFEuJP_!!1114217613.jpg'
            ]
        }

        df = pd.DataFrame(data)

        # 创建一个新的 Excel 工作簿
        wb = Workbook()
        ws = wb.active

        # 将 DataFrame 写入工作表
        for r in dataframe_to_rows(df, index=False, header=True):
            ws.append(r)

        # 定义图片所在的列
        image_column = 1

        # 从第 2 行开始（排除表头）
        for row, image_url in enumerate(df['Image URL'], start=2):
            response = requests.get(image_url)
            img = Image.open(BytesIO(response.content))
            img.thumbnail((100, 100))  # 缩小图片尺寸，如果需要的话
            img.save(f'image{row}.png', format='PNG')

            img_openpyxl = openpyxl_image(f'image{row}.png')
            ws.column_dimensions[chr(ord("A") + image_column - 1)].width = img_openpyxl.width // 5
            ws.row_dimensions[row].height = img_openpyxl.height
            ws.add_image(img_openpyxl, f'{chr(ord("A") + image_column + 1)}{row}')
        ws.delete_cols(2)
        wb.save('output.xlsx')

    def test_get_competing_key(self):
        """
        self.page, target_goods, self.ignore_keys,
        competing_min_roi=self.competing_min_roi,
        competing_min_visits=self.competing_min_visits,
        is_test_execute=self.is_test_execute,
        key_is_not_contain_letter=self.key_is_not_contain_letter
        :return:
        """
        page, _ = Login(param_.get("tbAccount"), param_.get('tbPassword')).execute()
        ignore_keys = param_['ignoreKeys']

        ignore_name_list = [ignoreNameList for ignoreNameList in param_['categorySearchList']]
        contain_name_list = param_['containNameList']

        category_search_list = [CategorySearch(name='炒锅', ignore_name_list=ignore_name_list
                                               , contain_name_list=contain_name_list, date_cycle='7天')]
        path = CompetitorGoodKey(page, ignore_keys=ignore_keys, competing_min_visits=10, is_test_execute=True,
                                 category_search_list=category_search_list, key_is_not_contain_letter=True)()
        print(path)

    def test_taskMapping(self):
        task_gjc_hyc_run(param_)

    def test_autoTask_data_clean_main(self):
        param = dict(param_.get('param'))
        gjc_hyc_data(params_data=param)

    def test_autoTask_gjc_hyc_main_run(self):
        param = dict(param_.get('param'))
        run(params=param,
            competing_path=[r'D:\python_code\drissionpage\taskTemplateExcel\gjc\competitorGoodKey\result'])

    def test_aaa(self):
        page = create_page()
        market_price_list = page.eles("x://tbody/tr[contains(@class, 'hYME_')]/td[contains(@mxa, ':o')]/text()")
        for index, market_price in enumerate(market_price_list):
            # 这个循环是检查是否有超出价格上限的词，如果有就修改
            # market_price = float(str(market_price).replace('元', ''))
            # print(market_price.text())
            print(market_price.replace('元', ''))
            market_price = float(market_price.replace('元', ''))
            print(market_price)

    def test_del_sheet(self):
        gjc_wb = xw.Book(r'D:\python_code\drissionpage\DownloadData\sycm_table\gjc_hyc_data_clean\result'
                         r'\gjc_hyc_data_2023-05-20_21-26-17.xlsx')
        xw_del_sheet(gjc_wb, '关键词+竞品词')
        gjc_wb.save()

    def test_login(self):
        page = create_page()
        # page.close_other_tabs()
        param = dict(param_.get('param'))
        Login(param.get("account"), param.get('password'), page=page).execute()

    def test_bring_chrome_to_foreground(self):
        try:
            # 获取 Chrome 窗口的标题
            chrome_windows = gw.getWindowsWithTitle("Chrome")
            if not chrome_windows:
                print("没有找到 Chrome 窗口")
                return
            # 选择第一个 Chrome 窗口
            chrome_window = chrome_windows[0]
            # 使用 pywinauto 连接到 Chrome 进程
            app = application.Application(backend="uia").connect(handle=chrome_window._hWnd)
            # 将 Chrome 窗口置于前台
            app.top_window().set_focus()
        except Exception as e:
            print(f"无法将 Chrome 置于前台: {e}")

    @retrying.retry(stop_max_attempt_number=3, wait_fixed=3000)
    def test_retry(self):
        num = random.randint(0, 10)
        if num < 8:
            print(num)
            raise ValueError('something went wrong')
        else:
            print('do_something succeeded')




